<template>
  <a-modal
    v-model:open="open"
    title="图片裁切"
    ok-text="确定"
    centered
    :z-index="2000"
    @ok="handleOk"
  >
    <div class="m-[20px_0px_20px_0px] h-[400px] overflow-hidden rounded-[6px]">
      <cropper
        ref="cropperRef"
        :src="img"
        class="cropper"
        :stencil-props="{
          aspectRatio: 1
        }"
        @change="change"
      />
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { Cropper } from 'vue-advanced-cropper';
import 'vue-advanced-cropper/dist/style.css';
import { message } from 'ant-design-vue';

const open = ref<boolean>(false);
const img = ref<string>('');
const cropperRef = ref<InstanceType<typeof Cropper> | null>(null);
// 存储当前裁切的坐标信息
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const currentCoordinates = ref<any>(null);

// 定义事件，用于传递裁切后的图片
const emit = defineEmits<{
  (e: 'cropped', imageUrl: string): void;
}>();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const change = ({ coordinates }: { coordinates: any }) => {
  currentCoordinates.value = coordinates;
};

/**
 * 处理确定按钮
 */
const handleOk = () => {
  if (!cropperRef.value) {
    message.error('裁切器未初始化');
    return;
  }

  try {
    // 获取裁切后的 canvas
    const canvas = cropperRef.value.getResult();
    if (!canvas || !canvas.canvas) {
      message.error('请先裁切图片');
      return;
    }

    // 将 canvas 转换为 base64
    const croppedImageUrl = canvas.canvas.toDataURL('image/jpeg', 0.9);

    // 触发事件，传递裁切后的图片
    emit('cropped', croppedImageUrl);

    // 关闭弹窗
    open.value = false;
    message.success('图片裁切成功');
  } catch (error) {
    console.error('裁切失败：', error);
    message.error('图片裁切失败');
  }
};

/**
 * 显示弹窗
 * @param imageUrl 要裁切的图片URL（base64或URL）
 */
const showModal = (imageUrl?: string) => {
  if (imageUrl) {
    img.value = imageUrl;
  }
  open.value = true;
};

// 暴露 showModal 方法
defineExpose({
  showModal
});
</script>

<style lang="scss" scoped>
.cropper {
  width: 100%;
  height: 100%;
}

:deep(.cropper-container) {
  width: 100% !important;
  height: 100% !important;
}
</style>
